package com.xcdh.ittools.type;

import com.xcdh.ittools.config.ITToolConfiguration;
import com.xcdh.ittools.handler.ITToolParameterHandler;
import com.xcdh.ittools.sql.ITToolBoundSql;
import com.xcdh.ittools.utils.MysqlDbUtil;
import com.xcdh.ittools.wrapper.DBColumnWrapper;
import lombok.extern.slf4j.Slf4j;


import java.sql.*;
import java.util.List;

@Slf4j
public class ITToolExecutor {
    private ITToolConfiguration configuration;
    private ITToolBoundSql boundSql ;

    public ITToolExecutor(ITToolConfiguration itToolConfiguration , ITToolBoundSql boundSql){
        this.configuration = itToolConfiguration ;
        this.boundSql = boundSql ;
    }

    public <T> T query(){
        Connection conn = null ;
        PreparedStatement statement = null ;
        ResultSet resultSet = null ;
        try {
            conn = this.configuration.getConnection();
            String sql = boundSql.getSql() ;
            statement = conn.prepareStatement(sql);
            ITToolParameterHandler parameterHandler = new ITToolParameterHandler(boundSql);
            /*===设置参数===*/
            parameterHandler.setParameters(statement);
            log.debug("parseSQl ===>{}",statement);
            statement.execute() ;
            ResultSetMetaData metaData = statement.getMetaData();
            resultSet = statement.getResultSet();
            List<DBColumnWrapper> wrapper = MysqlDbUtil.getDBColumnWrapper(metaData);
            ITToolsResultHandler handler = new ITToolsResultHandler(
                    this.configuration.getItToolReturnType() ,
                    wrapper ,
                    this.configuration
            ) ;
            return (T) handler.getResult(statement.getResultSet());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            MysqlDbUtil.closeResource(resultSet , statement , conn);
        }
    }
}
